import sys
import os
import time
import threading
import cv2
import pyprind

#基类
class CharFrame:

	ascii_char = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
	#映射到字符
	def pixelToChar(self, luminance):
		return self.ascii_char[int(luminance/256*len(self.ascii_char))]

	def convert(self, img, limitsize = -1, fill = False, wrap = False):
		if limitsize != -1 and (img.shape[0] > limitsize[1] or img.shape[1] > limitsize[0]):
			img = cv2.resize(img, limitsize, interpolation = cv2.INTER_AREA)
		ascii_frame = ''
		blank = ''
		if fill:
			blank += ' '*(limitsize[0]-img.shape[1])
		if wrap:
			blank += '\n'
		for i in range (img.shape[0]):
			for j in range(img.shape[1]):
				ascii_frame += self.pixelToChar(img[i,j])
			ascii_frame += blank
		return ascii_frame

class I2Char(CharFrame):
	
	result = None
	def __init__(self, path, limitsize = -1, fill = False, wrap = False):
		self.genCharImage(path, limitsize, fill, wrap)

	#图片转字符串函数
	def genCharImage(self, path, limitsize = -1, fill = False, wrap = False):
		self.result = ''
		#读取图片文件并赋值给cap
		cap = cv2.VideoCapture(path)
		#因为图片只有一帧，读取第一帧并转化为灰度图
		rawFrame = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2GRAY)
		#调用conver函数，获得转化后的字符串
		self.result = self.convert(rawFrame,limitsize = (100, 80), fill = True, wrap = True)
		cap.release()
	
	#保存转化后的字符串到
	def export(self):
		if not self.result:
			return
		with open('./out.txt', 'w') as f:
			f.write(self.result)


	def play(self):
		print(self.result)

if __name__ == '__main__':
	import argparse
	parser = argparse.ArgumentParser()
	parser.add_argument('file',
						help = 'Video file or charvideo file')
	parser.add_argument('-e', '--export', nargs = '?', const = 'charvideo.txt',
                        help='Export charvideo file')
    # 获取参数
	args = parser.parse_args()
	#创建I2Char实例
	i2Char = I2Char(args.file)
	#输出字符串
	i2Char.play()
	#保存文件
	i2Char.export()